from django.db import models
from django.contrib.auth.models import (
    BaseUserManager, AbstractBaseUser, PermissionsMixin
)
from django.contrib.auth.models import User
import datetime


# Create your models here.


class IDC(models.Model):
    name = models.CharField(max_length=64, unique=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = 'IDC'
        verbose_name_plural = 'IDC'


class Department(models.Model):
    name = models.CharField(max_length=64, unique=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '部门'
        verbose_name_plural = '部门'


class Hosts(models.Model):
    '''存储所有主机'''
    hostname = models.CharField(max_length=64)
    ip_addr = models.GenericIPAddressField(unique=True)
    post = models.PositiveSmallIntegerField(default=22)
    idc = models.ForeignKey("IDC")

    enabled = models.BooleanField(default=True, help_text='主机若不想被用户访问可以去掉此选项')
    memo = models.CharField(max_length=128, blank=True, null=True, )
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.ip_addr

    class Meta:
        verbose_name = '主机'
        verbose_name_plural = '主机'


class HostGroups(models.Model):
    '''主机组'''
    name = models.CharField(max_length=64, unique=True)
    bind_hosts = models.ManyToManyField('BindHosts', blank=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '主机组'
        verbose_name_plural = '主机组'


class HostUsers(models.Model):
    '''存储远程用户名密码'''
    username = models.CharField(max_length=64)
    auth_method_choices = (('ssh-password', "SSH/ Password"), ('ssh-key', "SSH/KEY"))
    auth_method = models.CharField(choices=auth_method_choices, max_length=16,
                                   help_text='如果选择SSH/KEY，请确保你的私钥文件已在settings.py中指定')
    password = models.CharField(max_length=126, blank=True, null=True)
    memo = models.CharField(max_length=128, blank=True, null=True)

    def __str__(self):
        return "%s(%s)" % (self.username, self.password)

    class Meta:
        unique_together = ('username', 'auth_method', 'password')
        verbose_name = '远程用户'
        verbose_name_plural = '远程用户'


class BindHosts(models.Model):
    host = models.ForeignKey('Hosts')
    host_user = models.ForeignKey('HostUsers', verbose_name="远程用户")

    enabled = models.BooleanField(default=True)

    def __str__(self):
        return '%s:%s' % (self.host.hostname, self.host_user.username)

    class Meta:
        unique_together = ("host", "host_user")
        verbose_name = '主机与远程用户绑定'
        verbose_name_plural = '主机远程与用户绑定'


# class UserProfile(models.Model):
#     '''堡垒机账户'''

class UserProfileManager(BaseUserManager):
    def create_user(self, email, name, password=None):
        """
        Creates and saves a User with the given email, date of
        birth and password.
        """
        if not email:
            raise ValueError('Users must have an email address')

        user = self.model(
            email=self.normalize_email(email),
            name=name,
        )

        user.set_password(password)
        user.is_active = True
        user.save(using=self._db)
        return user

    def create_superuser(self, email, name, password):
        """
        Creates and saves a superuser with the given email, date of
        birth and password.
        """
        user = self.create_user(
            email,
            password=password,
            name=name,
        )
        user.is_admin = True
        user.is_active = True
        user.save(using=self._db)
        return user


class UserProfile(AbstractBaseUser, PermissionsMixin):
    '''堡垒机账户'''
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    name = models.CharField(max_length=32)
    department = models.ForeignKey('Department', verbose_name='部门', blank=True, null=True)
    host_groups = models.ManyToManyField('HostGroups', verbose_name='授权主机组', blank=True)
    bind_hosts = models.ManyToManyField('BindHosts', verbose_name='授权主机', blank=True)
    memo = models.TextField(verbose_name='备注', blank=True, null=True, default=None)
    date_joined = models.DateTimeField(blank=True, null=True, auto_now_add=True)
    # valid_begin_time = models.DateTimeField(default=django.utils.timezone.now,help_text="yyyy-mm-dd HH:MM:SS")
    # valid_end_time = models.DateTimeField(blank=True,null=True,help_text="yyyy-mm-dd HH:MM:SS")

    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

    objects = UserProfileManager()

    USERNAME_FIELD = 'email'  # 用作用户名
    REQUIRED_FIELDS = ['name']  # 必填

    def get_full_name(self):
        # The user is identified by their email address
        return self.email

    def get_short_name(self):
        # The user is identified by their email address
        return self.email

    def __str__(self):  # __unicode__ on Python 2
        return self.email

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        # Simplest possible answer: All admins are staff
        #  return self.is_admin
        return self.is_active

    class Meta:
        verbose_name = '用户信息'
        verbose_name_plural = "用户信息"


class Session(models.Model):
    '''生成用户操作session id '''
    user = models.ForeignKey('UserProfile')
    bind_host = models.ForeignKey('BindHosts')
    tag = models.CharField(max_length=128, default='n/a')
    closed = models.BooleanField(default=False)
    cmd_count = models.IntegerField(default=0)  # 命令执行数量
    stay_time = models.IntegerField(default=0, help_text="每次刷新自动计算停留时间", verbose_name="停留时长(seconds)")
    date = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return '<id:%s user:%s bind_host:%s>' % (self.id, self.user.email, self.bind_host.host)

    class Meta:
        verbose_name = '审计日志'
        verbose_name_plural = '审计日志'


class Task(models.Model):
    '''批量任务记录表'''
    user = models.ForeignKey("UserProfile")
    task_type_choices = ((0, 'cmd'), (1, 'file_send'), (2, 'file_get'))
    task_type = models.SmallIntegerField(choices=task_type_choices)
    content = models.TextField(verbose_name="任务内容")
    date = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return "%s %s" % (self.task_type, self.content)


class TaskLogDetail(models.Model):
    task = models.ForeignKey("Task")
    bind_host = models.ForeignKey("BindHosts")
    result = models.TextField()

    status_choice = ((0, 'success'), (1, 'failed'), (2, 'init'))
    status = models.SmallIntegerField(choices=status_choice)

    start_date = models.DateTimeField(auto_now_add=True)
    end_date = models.DateTimeField(blank=True,null=True)

    def __str__(self):
        return "%s %s" % (self.bind_host, self.status)



